package com.ruoyi.business.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.domain.bo.HisDormitoryBo;
import com.ruoyi.business.service.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import io.swagger.v3.core.util.Json;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 退宿舍
 *
 * @author songzhengsheng
 * @date 2023-06-29
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/business/hisdormitory")
public class HisDormitoryController extends BaseController {

    private final IHisDormitoryService iHisDormitoryService;
    private final IDormitoryPlusService dormitoryPlusService;
    private final IBedsPlusService bedsPlusService;
    private final IEmployeePlusService employeePlusService;
    private final IDegreesService iDegreesService;
    private final ISysNoticeService sysNoticeService;
    /**
     * 查询退宿舍列表
     */
    @GetMapping("/list")
    public TableDataInfo<HisDormitory> list(HisDormitory entity) {
        startPage();
        List<HisDormitory> list = iHisDormitoryService.getList(entity);
        return getDataTable(list);
    }

    /**
     * 导出退宿舍列表
     */
    @Log(title = "导出退宿舍列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HisDormitory entity, HttpServletResponse response) {
        LambdaQueryWrapper<HisDormitory> lqw =iHisDormitoryService.buildQueryWrapper(entity);
        List<HisDormitory> list = iHisDormitoryService.list(lqw);
        ExcelUtil.exportExcel(list, "退宿舍", HisDormitory.class, response);
    }

    /**
     * 获取退宿舍详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<HisDormitory> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iHisDormitoryService.getById(id));
    }

    /**
     * 新增退宿舍
     */
    @Transactional(rollbackFor = Exception.class)
    @Log(title = "退宿舍", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public AjaxResult add(@RequestBody HisDormitory bo) {
        List<HisDormitoryBo> images=bo.getImages();
        if (images!=null){
            List<String> urls=new ArrayList<String>();
            for (HisDormitoryBo hb : images) {
                urls.add(hb.getUrl());
            }
            bo.setPicurl(urls.toString());
        }

        //先清空之前的床位
        LambdaQueryWrapper<Beds> query = new LambdaQueryWrapper<>();
        query.eq(Beds::getDormitoryId,bo.getDormitoryid());
        query.eq(Beds::getStatus,"已占位");
        List<Long> employeeIds = bedsPlusService.list(query).stream().map(Beds::getEmployeeId).collect(Collectors.toList());
        if (employeeIds.size()>0){


            bo.setEmployeeids(employeeIds.toString());
            iHisDormitoryService.save(bo);

            LambdaUpdateWrapper<Beds> update_beds_sql = new LambdaUpdateWrapper<Beds>().set(Beds::getEmployeeId,null).set(Beds::getStatus,"空位").set(Beds::getUpdateTime,new DateTime()).eq(Beds::getDormitoryId,bo.getDormitoryid());
            bedsPlusService.update(update_beds_sql);
            //电表抄表
            Degrees degrees=new Degrees();
            degrees.setDormitoryid(bo.getDormitoryid());
            degrees.setReadDate(bo.getReadDate());
            degrees.setNumberdegrees(bo.getNumberdegrees());
            iDegreesService.save(degrees);
            //发通知
            for (Long employeeid:employeeIds) {
                Employee employeeModel=employeePlusService.getById(employeeid);
                SysNotice notice=new SysNotice();
                String noticeTitle = String.format("%s 已被退出宿舍", employeeModel.getFullName());
                notice.setNoticeTitle(noticeTitle);
                notice.setNoticeType("退宿");
                notice.setStatus("0");
                notice.setDepartment(employeeModel.getDepartment());
                notice.setRoomNumber(bedsPlusService.getbedDetailByid(employeeModel.getRoomNumber()));
                sysNoticeService.insertNotice(notice);
            }
            LambdaUpdateWrapper<Employee> update_Employee_sql = new LambdaUpdateWrapper<Employee>().set(Employee::getRoomNumber,null).set(Employee::getAllocated,null).in(Employee::getId,employeeIds);
            employeePlusService.update(update_Employee_sql);
            return success("操作成功");
        }

        return error("无效操作，空宿舍");
    }

    /**
     * 修改退宿舍
     */
    @Log(title = "退宿舍", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody HisDormitory bo) {
        return toAjax(iHisDormitoryService.updateById(bo));
    }

    /**
     * 删除退宿舍
     *
     * @param ids 主键串
     */
    @Log(title = "退宿舍", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iHisDormitoryService.removeBatchByIds(Arrays.asList(ids), true));
    }

    /**
     * 根据id获取人员详细信息
     *
     * @param id 主键
     */
    @GetMapping("/getEmployeeInfoByid/{id}")
    public R<List<Employee>> getEmployeeInfoByid(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        HisDormitory hisDormitoryModel=iHisDormitoryService.getById(id);
        if (hisDormitoryModel.getEmployeeids()!=null){
            String[] employeeIds = hisDormitoryModel.getEmployeeids().replace("[","").replace("]","").trim().split(",");
            LambdaQueryWrapper<Employee> query = new LambdaQueryWrapper<>();
            query.in(Employee::getId,employeeIds);
            List<Employee> employeeList=employeePlusService.list(query);
            return R.ok(employeeList);
        }
        return R.ok();
    }
}
